<template>
    <div class="scenario-select-page">
        <!-- 导航栏 -->
        <van-nav-bar title="Choose Scenario" left-text="Back" left-arrow @click-left="handleBack">
            <template #right>
                <van-icon name="filter-o" @click="showFilterPopup" />
            </template>
        </van-nav-bar>

        <!-- 选中的角色信息 -->
        <div class="selected-character" v-if="selectedCharacter">
            <div class="character-info">
                <van-image :src="selectedCharacter.avatar_url || '/default-character.png'" round width="40"
                    height="40" />
                <div class="character-details">
                    <div class="character-name">Training with {{ selectedCharacter.name }}</div>
                    <div class="character-personality">{{ selectedCharacter.personality_type }}</div>
                </div>
            </div>
            <van-button size="small" @click="changeCharacter">Change</van-button>
        </div>

        <!-- 搜索栏 -->
        <div class="search-section">
            <van-search v-model="searchQuery" placeholder="Search scenarios..." @search="handleSearch"
                @clear="handleClearSearch" />
        </div>

        <!-- 筛选标签 -->
        <div class="filter-section" v-if="activeFilters.length > 0">
            <div class="filter-tags">
                <van-tag v-for="filter in activeFilters" :key="filter.key" closeable @close="removeFilter(filter.key)"
                    size="small" type="primary">
                    {{ filter.label }}
                </van-tag>
            </div>
        </div>

        <!-- 场景分类标签 -->
        <div class="category-tabs">
            <van-tabs v-model:active="activeCategory" @change="handleCategoryChange">
                <van-tab title="All" name="all" />
                <van-tab title="Social" name="social" />
                <van-tab title="Business" name="business" />
                <van-tab title="Casual" name="casual" />
                <van-tab title="Conflict" name="conflict" />
            </van-tabs>
        </div>

        <!-- 场景列表 -->
        <div class="scenarios-section">
            <!-- 加载状态 -->
            <div v-if="loading" class="loading-section">
                <van-loading size="24px" vertical>Loading scenarios...</van-loading>
            </div>

            <!-- 场景列表 -->
            <div v-else-if="filteredScenarios.length > 0" class="scenarios-list">
                <ScenarioCard v-for="scenario in filteredScenarios" :key="scenario.id" :scenario="scenario"
                    :selected="selectedScenario?.id === scenario.id" @select="selectScenario"
                    @favorite="toggleFavorite" />
            </div>

            <!-- 空状态 -->
            <van-empty v-else description="No scenarios found" image="search">
                <van-button type="primary" @click="clearAllFilters">
                    Clear Filters
                </van-button>
            </van-empty>
        </div>

        <!-- 底部操作栏 -->
        <div class="bottom-actions" v-if="selectedScenario">
            <div class="selected-info">
                <div class="selected-details">
                    <div class="selected-title">{{ selectedScenario.title || selectedScenario.name }}</div>
                    <div class="selected-meta">
                        <span>{{ selectedScenario.estimated_duration || 15 }}min</span>
                        <span>•</span>
                        <span>{{ selectedScenario.difficulty || 'Medium' }}</span>
                    </div>
                </div>
            </div>
            <van-button type="primary" size="large" @click="startTraining" :loading="starting">
                Start Training
            </van-button>
        </div>

        <!-- 筛选弹窗 -->
        <van-popup v-model:show="showFilter" position="bottom" :style="{ height: '60%' }" round closeable
            close-icon-position="top-right">
            <div class="filter-popup">
                <div class="filter-header">
                    <h3>Filter Scenarios</h3>
                </div>

                <div class="filter-content">
                    <!-- 难度筛选 -->
                    <div class="filter-group">
                        <h4>Difficulty Level</h4>
                        <van-checkbox-group v-model="filterOptions.difficulty">
                            <van-checkbox name="beginner">Beginner</van-checkbox>
                            <van-checkbox name="intermediate">Intermediate</van-checkbox>
                            <van-checkbox name="advanced">Advanced</van-checkbox>
                        </van-checkbox-group>
                    </div>

                    <!-- 时长筛选 -->
                    <div class="filter-group">
                        <h4>Duration</h4>
                        <van-checkbox-group v-model="filterOptions.duration">
                            <van-checkbox name="short">Short (< 10min)</van-checkbox>
                                    <van-checkbox name="medium">Medium (10-20min)</van-checkbox>
                                    <van-checkbox name="long">Long (> 20min)</van-checkbox>
                        </van-checkbox-group>
                    </div>

                    <!-- 其他筛选 -->
                    <div class="filter-group">
                        <h4>Other</h4>
                        <van-checkbox v-model="filterOptions.favoritesOnly">
                            Show favorites only
                        </van-checkbox>
                        <van-checkbox v-model="filterOptions.popularOnly">
                            Popular scenarios only
                        </van-checkbox>
                    </div>
                </div>

                <div class="filter-actions">
                    <van-button block @click="clearFilters">Clear All</van-button>
                    <van-button type="primary" block @click="applyFilters">
                        Apply Filters
                    </van-button>
                </div>
            </div>
        </van-popup>
    </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { showToast } from 'vant'
import { trainingApi, type TrainingScenario, type AiCharacter } from '@/api'
import ScenarioCard from '@/components/ScenarioCard.vue'

const router = useRouter()

// 响应式数据
const loading = ref(true)
const starting = ref(false)
const searchQuery = ref('')
const showFilter = ref(false)
const activeCategory = ref('all')
const scenarios = ref<TrainingScenario[]>([])
const selectedScenario = ref<TrainingScenario | null>(null)
const selectedCharacter = ref<AiCharacter | null>(null)

// 筛选选项
const filterOptions = ref({
    difficulty: [] as string[],
    duration: [] as string[],
    favoritesOnly: false,
    popularOnly: false
})

// 计算属性
const activeFilters = computed(() => {
    const filters: Array<{ key: string; label: string }> = []

    if (filterOptions.value.difficulty.length > 0) {
        filters.push({
            key: 'difficulty',
            label: `Difficulty: ${filterOptions.value.difficulty.length} selected`
        })
    }

    if (filterOptions.value.duration.length > 0) {
        filters.push({
            key: 'duration',
            label: `Duration: ${filterOptions.value.duration.length} selected`
        })
    }

    if (filterOptions.value.favoritesOnly) {
        filters.push({
            key: 'favorites',
            label: 'Favorites only'
        })
    }

    if (filterOptions.value.popularOnly) {
        filters.push({
            key: 'popular',
            label: 'Popular only'
        })
    }

    return filters
})

const filteredScenarios = computed(() => {
    let filtered = scenarios.value

    // 分类筛选
    if (activeCategory.value !== 'all') {
        filtered = filtered.filter(scenario =>
            scenario.category?.toLowerCase() === activeCategory.value.toLowerCase()
        )
    }

    // 搜索筛选
    if (searchQuery.value.trim()) {
        const query = searchQuery.value.toLowerCase()
        filtered = filtered.filter(scenario =>
            scenario.title?.toLowerCase().includes(query) ||
            scenario.description?.toLowerCase().includes(query) ||
            scenario.category?.toLowerCase().includes(query) ||
            scenario.skills?.some(skill => skill.toLowerCase().includes(query)) ||
            scenario.tags?.some(tag => tag.toLowerCase().includes(query))
        )
    }

    // 难度筛选
    if (filterOptions.value.difficulty.length > 0) {
        filtered = filtered.filter(scenario =>
            scenario.difficulty && filterOptions.value.difficulty.includes(scenario.difficulty.toLowerCase())
        )
    }

    // 时长筛选
    if (filterOptions.value.duration.length > 0) {
        filtered = filtered.filter(scenario => {
            const duration = scenario.estimated_duration || 15 // 默认15分钟
            return filterOptions.value.duration.some(range => {
                switch (range) {
                    case 'short':
                        return duration < 10
                    case 'medium':
                        return duration >= 10 && duration <= 20
                    case 'long':
                        return duration > 20
                    default:
                        return true
                }
            })
        })
    }

    // 收藏筛选
    if (filterOptions.value.favoritesOnly) {
        filtered = filtered.filter(scenario => scenario.is_favorited)
    }

    // 热门筛选
    if (filterOptions.value.popularOnly) {
        filtered = filtered.filter(scenario => scenario.is_popular)
    }

    return filtered
})

// 方法
const loadScenarios = async () => {
    try {
        loading.value = true
        const response = await trainingApi.getScenarios()
        scenarios.value = response.data
    } catch (error) {
        console.error('Failed to load scenarios:', error)
        showToast('Failed to load scenarios')
    } finally {
        loading.value = false
    }
}

const selectScenario = (scenario: TrainingScenario) => {
    selectedScenario.value = scenario
}

const toggleFavorite = async (scenario: TrainingScenario) => {
    try {
        // TODO: 实现场景收藏API
        scenario.is_favorited = !scenario.is_favorited
        showToast({
            type: 'success',
            message: scenario.is_favorited ? 'Added to favorites' : 'Removed from favorites'
        })
    } catch (error) {
        console.error('Failed to toggle favorite:', error)
        showToast('Failed to update favorite')
    }
}

const startTraining = async () => {
    if (!selectedCharacter.value || !selectedScenario.value) return

    try {
        starting.value = true

        // 创建训练会话
        const response = await trainingApi.createSession({
            ai_character_id: selectedCharacter.value.id,
            training_scenario_id: selectedScenario.value.id
        })

        // 跳转到训练对话页面
        router.push({
            name: 'TrainingChat',
            params: { sessionId: response.data.id }
        })
    } catch (error) {
        console.error('Failed to start training:', error)
        showToast('Failed to start training')
    } finally {
        starting.value = false
    }
}

const handleCategoryChange = () => {
    // 分类变化逻辑已在computed中处理
}

const handleSearch = () => {
    // 搜索逻辑已在computed中处理
}

const handleClearSearch = () => {
    searchQuery.value = ''
}

const showFilterPopup = () => {
    showFilter.value = true
}

const removeFilter = (filterKey: string) => {
    switch (filterKey) {
        case 'difficulty':
            filterOptions.value.difficulty = []
            break
        case 'duration':
            filterOptions.value.duration = []
            break
        case 'favorites':
            filterOptions.value.favoritesOnly = false
            break
        case 'popular':
            filterOptions.value.popularOnly = false
            break
    }
}

const clearFilters = () => {
    filterOptions.value = {
        difficulty: [],
        duration: [],
        favoritesOnly: false,
        popularOnly: false
    }
}

const clearAllFilters = () => {
    clearFilters()
    searchQuery.value = ''
    activeCategory.value = 'all'
}

const applyFilters = () => {
    showFilter.value = false
}

const changeCharacter = () => {
    router.push('/training/character-select')
}

const handleBack = () => {
    router.back()
}

// 生命周期
onMounted(async () => {
    // 从路由参数获取角色ID
    const characterId = router.currentRoute.value.query.characterId

    if (!characterId) {
        // 如果没有角色ID，跳转到角色选择页面
        router.push('/training/character-select')
        return
    }

    try {
        // 根据ID获取角色信息
        const charactersResponse = await trainingApi.getCharacters()
        selectedCharacter.value = charactersResponse.data.find(
            char => char.id === parseInt(characterId as string)
        ) || null

        if (!selectedCharacter.value) {
            router.push('/training/character-select')
            return
        }
    } catch (error) {
        console.error('Failed to load character:', error)
        router.push('/training/character-select')
        return
    }

    loadScenarios()
})
</script>

<style lang="scss" scoped>
.scenario-select-page {
    min-height: 100vh;
    background: #f7f8fa;
    padding-bottom: 100px;

    .selected-character {
        background: white;
        padding: 16px;
        border-bottom: 1px solid #ebedf0;
        display: flex;
        justify-content: space-between;
        align-items: center;

        .character-info {
            display: flex;
            align-items: center;
            gap: 12px;

            .character-details {
                .character-name {
                    font-size: 16px;
                    font-weight: 600;
                    color: #323233;
                }

                .character-personality {
                    font-size: 12px;
                    color: #646566;
                }
            }
        }
    }

    .search-section {
        padding: 16px;
        background: white;
        border-bottom: 1px solid #ebedf0;
    }

    .filter-section {
        padding: 12px 16px;
        background: white;
        border-bottom: 1px solid #ebedf0;

        .filter-tags {
            display: flex;
            gap: 8px;
            flex-wrap: wrap;
        }
    }

    .category-tabs {
        background: white;
        border-bottom: 1px solid #ebedf0;

        :deep(.van-tabs__nav) {
            padding: 0 16px;
        }
    }

    .scenarios-section {
        padding: 16px;

        .loading-section {
            display: flex;
            justify-content: center;
            align-items: center;
            height: 200px;
        }

        .scenarios-list {
            display: flex;
            flex-direction: column;
            gap: 16px;
        }
    }

    .bottom-actions {
        position: fixed;
        bottom: 0;
        left: 0;
        right: 0;
        background: white;
        padding: 16px;
        border-top: 1px solid #ebedf0;
        display: flex;
        align-items: center;
        gap: 16px;
        box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.1);

        .selected-info {
            flex: 1;

            .selected-details {
                .selected-title {
                    font-size: 16px;
                    font-weight: 600;
                    color: #323233;
                    margin-bottom: 4px;
                }

                .selected-meta {
                    font-size: 12px;
                    color: #646566;

                    span {
                        margin-right: 4px;
                    }
                }
            }
        }
    }

    .filter-popup {
        padding: 20px;
        height: 100%;
        display: flex;
        flex-direction: column;

        .filter-header {
            margin-bottom: 20px;

            h3 {
                font-size: 18px;
                font-weight: 600;
                color: #323233;
                margin: 0;
            }
        }

        .filter-content {
            flex: 1;
            overflow-y: auto;

            .filter-group {
                margin-bottom: 24px;

                h4 {
                    font-size: 16px;
                    font-weight: 500;
                    color: #323233;
                    margin: 0 0 12px 0;
                }

                .van-checkbox {
                    margin-bottom: 8px;
                }
            }
        }

        .filter-actions {
            display: flex;
            gap: 12px;
            padding-top: 16px;
            border-top: 1px solid #ebedf0;
        }
    }
}
</style>